const app = getApp();
const db = wx.cloud.database();
const cards = db.collection('card');

const Search = function () {
    this.i = 0;
    this.list = [];
};
Search.prototype = {
    pick(password, callback = function () { }) {
        cards.doc(password).get({
            success(res) {
                callback(res.data);
            }
        })
    },
    getCards({ keywords="", rule = {}, skip = 0, success = function () { },fail=function() {}, num = 0 }) {
        const _ = db.command;
        if (parseInt(keywords) && !rule) {
            if (parseInt(keywords).toString().length > 4) {
                this.pick(keywords, success);
                return;
            }
        }

        console.log('查询器收到的是：',keywords,rule,skip,num);
        const key = db.RegExp({
            regexp: ".*" + keywords + ".*",
            options: "s"
        });
        var rule_ = new Object();
        for (let key in rule) {
            if ((!rule[key] && rule[key] != 0) || rule[key] == "null") {
                continue;
            }
            if (rule[key] instanceof Array) {
                rule_[key] = _.and(_.gte(parseInt(rule[key][0])), _.lte(parseInt(rule[key][1])));
            }
            else {
                rule_[key] = _.eq(rule[key]);
            }
        }
        if (Object.getOwnPropertyNames(rule_).length>0) {
            var search = cards.where(_.and(rule_, _.or({ name: key }, { desc: key }))).orderBy('level', 'desc').orderBy('attack', 'desc').orderBy('_type', 'desc');
        }
        else {
            var search = cards.where(_.or({ name: key }, { desc: key })).orderBy('level', 'desc').orderBy('attack', 'desc').orderBy('_type', 'desc');
        }
        let skip_ = skip + (num > 0 ? 0 : (num - 1));
        if (skip_<0) {
            fail();
        }
        search = skip_ ? search.skip(skip_) : search;
        search.get({
            success(res) {
                success(num ? res.data.slice(0, Math.abs(num)) : res.data);
            },
            fail(err) {
                fail(err);
            }
        })
    },
    iter({ keywords, rule = {}, num = 20, skip=0, success = function () { }, fail = function () { },reset=false }) {
        if (reset) {
            this.list=[];
            this.i=0;
        }
        const that = this;
        skip = parseInt(skip);
        console.log("迭代器收到的是",keywords,rule,skip,num)
        this.getCards({
            keywords,
            success(res) {
                if (res.length > 0) {
                    that.list=that.list.concat(res);
                    that.i += num;
                    success(res);
                }
                else {
                    console.log('查找失败:1',res);
                    fail();
                }
            },
            fail(err) {
                console.log('查找失败:2',err);
                fail(err);
            },
            rule,
            skip: skip + this.i,
            num: num
        })
    },
    get list_() {
        const card = require('./card.js');
        let list=[];
        this.list.forEach((c,i,l)=> {
            list.push(new card.Card(c));
        })
        return list;
    }
}

const Rule = function ({ keywords = '', rule = {}, skip=0 }) {
    this.keywords = keywords ? keywords:'';
    this.rule = rule?rule:{};
    this.skip=skip;
};
Rule.prototype = {
    get zip() {
        let zip = 'keywords=' + this.keywords;
        for (let i in this.rule) {
            if (this.rule[i] instanceof Array) {
                zip += "&_array_" + i + "=" + JSON.stringify(this.rule[i]);
            }
            else if (this.rule[i]) {
                zip += "&" + i + "=" + this.rule[i];
            }
        }
        if (this.skip) {
            zip+='&skip='+this.skip;
        }
        return zip;
    },
    unzip(e) {
        let rule=new Object();
        for (let i in e) {
            if (i.slice(0,7)=='_array_') {
                rule[i.slice(7)] = JSON.parse(e[i])
            }
            else if (i == 'keywords') {}
            else if (i == 'skip') {}
            else if (i == 'password') {}
            else {
                rule[i]=e[i];
            }
        }
        return {keywords:e.keywords,rule,skip:e.skip?e.skip:0};
    }
}


module.exports.Search = Search;
module.exports.Rule = Rule;